import base64
import hashlib
import json
import random
import time
import jwt
from django.views import View
from django.conf import settings
from django.http import JsonResponse
from django.core.cache import caches
from user.models import UserProfile

def logging_check(func):
    def wrapper(self, request, *args, **kwargs):
        # token校验
        token = request.META.get('HTTP_AUTHORIZATION')
        if not token:
            return JsonResponse({'code':403, "error":"Please login in00"})
        # 校验token
        try:
            # payload:{'exp':xx, "username":xxx}
            payload = jwt.decode(token, key=settings.JWT_TOKEN_KEY, algorithms="HS256")
        except Exception as e:
            return JsonResponse({'code': 403, "error": "Please login in01"})
        # toekn校验不通过:{"code":403, "error":"xxxxxxxxxx"}
        username = payload.get('username')
        try:
            user = UserProfile.objects.get(username=username)
            # 给所有套过装饰器的方法的request参数，都增加一个myuser属性
            request.myuser = user
        except Exception as e:
            return JsonResponse({'code': 403, "error": "Please login in02"})
        request.data = json.loads(request.body) if request.body else None
        return func(self,request,*args, **kwargs)
    return wrapper











